package com.bsoft.hospitalchs.ui.login;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bsoft.hospitalchs.R;
import com.bsoft.hospitalchs.base.BaseActivity;
import com.bsoft.hospitalchs.common.MyApplication;
import com.bsoft.hospitalchs.model.RoleBean;
import com.bsoft.hospitalchs.ui.main.MainActivity;
import com.bsoft.hospitalchs.utils.RestartAPPTool;
import com.bsoft.hospitalchs.utils.SpUtils;
import com.bsoft.hospitalchs.utils.ToastUtils;
import com.bsoft.hospitalchs.widget.CustomProgress;
import com.bsoft.hospitalchs.widget.MtitlePopupWindow;
import com.bsoft.hospitalchs.widget.MtitlePopupWindow.OnPopupWindowClickListener;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 泅渡者
 * Created on 2017/5/10.
 */

public class LoginActivity extends BaseActivity<LoginContract.Presenter> implements LoginContract.View {

    @Bind(R.id.text_name)
    TextView textName;
    @Bind(R.id.tv_ipconfig)
    TextView tvIpconfig;
    @Bind(R.id.ll_ipconfig)
    LinearLayout llIpconfig;
    @Bind(R.id.login_box)
    ImageView loginBox;
    @Bind(R.id.edt_account)
    EditText edtAccount;
    @Bind(R.id.edt_pwd)
    EditText edtPwd;
    @Bind(R.id.tv_identity)
    TextView tvIdentity;
    @Bind(R.id.iv_reload)
    ImageView ivReload;
    @Bind(R.id.tv_nuit)
    TextView tvNuit;
    @Bind(R.id.cb_remember)
    CheckBox cbRemember;
    @Bind(R.id.btn_login)
    Button btnLogin;

    private MtitlePopupWindow mtitlePopupWindow;
    private static final int REQUEST_CODE_PERMISSION_SD = 101;
    private int urt = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        this.createPresenter(new LoginPresenter(this, this));
        checkPermission();

    }


    @Override
    public void hideLoading() {
        if (customProgress != null) {
            customProgress.dismiss();
        }
    }

    @Override
    public void showLoadingDialog() {
        customProgress = CustomProgress.show(this, "正在加载...", true, null);
    }


    @Override
    public void toJumpActivity() {
        startActivity(new Intent(this, MainActivity.class));
        this.finish();
    }

    /**
     * 角色选择弹窗
     *
     * @param roleBeen
     */
    @Override
    public void showPopupWindow(final List<RoleBean> roleBeen) {
        mtitlePopupWindow = new MtitlePopupWindow(this);
        mtitlePopupWindow.changeData(roleBeen);
        mtitlePopupWindow.showAsDropDown(tvIdentity);
        mtitlePopupWindow.setOnPopupWindowClickListener(new OnPopupWindowClickListener() {
            @Override
            public void onPopupWindowItemClick(int position) {
                SpUtils.put(MyApplication.getInstance(), "Character", roleBeen.get(position).getRole_name());
                SpUtils.put(MyApplication.getInstance(), "Department", roleBeen.get(position).getManageUni_name());
                SpUtils.put(MyApplication.getInstance(), "Urt", roleBeen.get(position).getRole_id() + "");
                SpUtils.put(MyApplication.getInstance(), "createUnit", roleBeen.get(position).getCreateUnit_id());
                presenter.toSetinfo(edtAccount, edtPwd, tvIdentity, tvNuit, MyApplication.isRemember());
            }
        });
    }

    @Override
    public void reLoad() {
        SpUtils.put(MyApplication.getInstance(), "UserName", edtAccount.getText().toString());
        SpUtils.put(MyApplication.getInstance(), "PassWord", edtPwd.getText().toString());
        SpUtils.put(MyApplication.getInstance(), "Character", "");
        SpUtils.put(MyApplication.getInstance(), "Department", "");
        SpUtils.put(MyApplication.getInstance(), "Urt", "");
        SpUtils.put(MyApplication.getInstance(), "createUnit", "");
        presenter.toSetinfo(edtAccount, edtPwd, tvIdentity, tvNuit, MyApplication.isRemember());
        presenter.toGetCharacter(true);
    }

    /**
     * 检测权限
     */
    public void checkPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            // 申请多个权限。
            AndPermission.with(LoginActivity.this)
                    .requestCode(REQUEST_CODE_PERMISSION_SD)
                    .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                    // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框，避免用户勾选不再提示。
                    .rationale(rationaleListener
                    )
                    .send();
        }
    }

    /**
     * 动态权限回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    /**
     * 授权成功
     *
     * @param grantedPermissions
     */
    @PermissionYes(REQUEST_CODE_PERMISSION_SD)
    private void getMultiYes(List<String> grantedPermissions) {
        tvIpconfig.setText(MyApplication.getInstance().getIpconfig() + "");
        presenter.toSetinfo(edtAccount, edtPwd, tvIdentity, tvNuit, MyApplication.isRemember());
        presenter.toSetRememberStatue(cbRemember);
        presenter.toUpdate();
    }

    /**
     * 授权失败
     *
     * @param deniedPermissions
     */
    @PermissionNo(REQUEST_CODE_PERMISSION_SD)
    private void getMultiNo(List<String> deniedPermissions) {

    }

    /**
     * 未授权，提示去设置
     */
    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
            // 自定义对话框。
            AlertDialog.build(LoginActivity.this)
                    .setTitle(R.string.title_dialog)
                    .setMessage(R.string.message_permission_rationale)
                    .setPositiveButton(R.string.btn_dialog_yes_permission, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.resume();
                        }
                    })

                    .setNegativeButton(R.string.btn_dialog_no_permission, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                            rationale.cancel();
                        }
                    })
                    .show();
        }
    };

    @OnClick({R.id.tv_identity, R.id.iv_reload, R.id.btn_login, R.id.ll_ipconfig})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_identity:
                break;
            case R.id.iv_reload:
                if (!TextUtils.isEmpty(edtAccount.getText().toString()) && !TextUtils.isEmpty(edtPwd.getText().toString())) {
                    if (edtAccount.getText().toString().equals(SpUtils.get(this, "UserName", ""))) {
                        presenter.toGetCharacter(false);
                    } else {
                        SpUtils.put(MyApplication.getInstance(), "UserName", edtAccount.getText().toString());
                        SpUtils.put(MyApplication.getInstance(), "PassWord", edtPwd.getText().toString());
                        SpUtils.put(MyApplication.getInstance(), "Character", "");
                        SpUtils.put(MyApplication.getInstance(), "Department", "");
                        SpUtils.put(MyApplication.getInstance(), "Urt", "");
                        SpUtils.put(MyApplication.getInstance(), "createUnit", "");
                        presenter.toSetinfo(edtAccount, edtPwd, tvIdentity, tvNuit, MyApplication.isRemember());
                        presenter.toGetCharacter(true);
                    }
                } else {
                    ToastUtils.showShort("用户名和密码不能为空！");
                }
                break;

            case R.id.btn_login:
                if (MyApplication.isRemember()) {
                    SpUtils.put(MyApplication.getInstance(), "PassWord", edtPwd.getText().toString());
                } else {
                    SpUtils.put(MyApplication.getInstance(), "PassWord", "");
                }
                String str = (String) SpUtils.get(MyApplication.getInstance(), "Urt", "");
                presenter.toLogin(str, edtAccount.getText().toString(), edtPwd.getText().toString(), "3", "0");
                break;
            case R.id.ll_ipconfig:
                final EditText view2 = new EditText(this);
                // 自定义对话框。
                AlertDialog.build(LoginActivity.this)
                        .setTitle("请输入IP地址及端口：")
                        .setMessage("改变IP会重新启动！")
                        .setView(view2)
                        .setNegativeButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (!TextUtils.isEmpty(view2.getText().toString())) {
                                    MyApplication.getInstance().setIpconfig(view2.getText().toString());
                                    tvIpconfig.setText(MyApplication.getInstance().getIpconfig());
                                    dialog.cancel();
                                    new Thread(new Runnable() {

                                        public void run() {

                                            try {
                                                Thread.sleep(1000);
                                                RestartAPPTool.restartAPP(LoginActivity.this);
                                            } catch (InterruptedException e) {
                                                e.printStackTrace();
                                            }

                                        }

                                    }).start();

                                } else {
                                    ToastUtils.showShort("Ip地址不能为空,请重新设置");
                                }

                            }
                        })
                        .show();
                break;
        }
    }


}
